/**
 * 用户控制器
 * 处理用户相关的数据库操作
 */

import { BaseController, ensureDbInit, createResponse, createErrorResponse } from './BaseController'
import database from '../../utils/database'
import { generateId } from '../../mock/utils'

export class UserController extends BaseController {
  constructor() {
    super('users')
  }
  
  /**
   * 用户登录（本地验证）
   */
  async login(data: { username: string; password: string }) {
    try {
      await ensureDbInit()
      const { username, password } = data
      
      const usersResult = await database.query(
        'SELECT * FROM users WHERE username = ? AND is_deleted = 0',
        [username]
      )
      
      if (usersResult.code !== 0) {
        return createErrorResponse(usersResult.message || '查询用户失败')
      }
      
      const users = usersResult.data || []
      if (users.length === 0) {
        return createErrorResponse('用户不存在', 1003)
      }
      
      // 简化的密码验证（实际项目中应该使用加密）
      const user = users[0]
      
      return createResponse({
        token: `sqlite_token_${user.id}_${Date.now()}`,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          nickname: user.nickname,
          avatar: user.avatar
        }
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '登录失败')
    }
  }
  
  /**
   * 用户注册
   */
  async register(data: {
    username: string
    email: string
    password: string
    nickname?: string
  }) {
    try {
      await ensureDbInit()
      const { username, email, password, nickname } = data
      
      // 检查用户名是否已存在
      const existingUsersResult = await database.query(
        'SELECT id FROM users WHERE username = ? OR email = ? AND is_deleted = 0',
        [username, email]
      )
      
      if (existingUsersResult.code !== 0) {
        return createErrorResponse(existingUsersResult.message || '检查用户是否存在失败')
      }
      
      const existingUsers = existingUsersResult.data || []
      if (existingUsers.length > 0) {
        return createErrorResponse('用户名或邮箱已存在', 1001)
      }
      
      const userId = generateId()
      const now = new Date().toISOString()
      
      await database.insert('users', {
        id: userId,
        username,
        email,
        nickname: nickname || username,
        avatar: '',
        phone: '',
        gender: 0,
        birthday: '',
        bio: '',
        settings: JSON.stringify({}),
        created_at: now,
        updated_at: now,
        is_deleted: 0
      })
      
      return createResponse({
        token: `sqlite_token_${userId}_${Date.now()}`,
        user: {
          id: userId,
          username,
          email,
          nickname: nickname || username,
          avatar: ''
        }
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '注册失败')
    }
  }
  
  /**
   * 获取用户信息
   */
  async getUserInfo() {
    try {
      await ensureDbInit()
      // 简化实现，返回第一个用户
      const usersResult = await database.query(
        'SELECT * FROM users WHERE is_deleted = 0 LIMIT 1'
      )
      
      if (usersResult.code !== 0) {
        return createErrorResponse(usersResult.message || '查询用户信息失败')
      }
      
      const users = usersResult.data || []
      if (users.length === 0) {
        return createErrorResponse('用户不存在', 1003)
      }
      
      const user = users[0]
      return createResponse({
        id: user.id,
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone,
        gender: user.gender,
        birthday: user.birthday,
        bio: user.bio,
        settings: user.settings ? JSON.parse(user.settings) : {}
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取用户信息失败')
    }
  }
  
  /**
   * 更新用户信息
   */
  async updateUserInfo(data: any) {
    try {
      await ensureDbInit()
      const usersResult = await database.query(
        'SELECT id FROM users WHERE is_deleted = 0 LIMIT 1'
      )
      
      if (usersResult.code !== 0) {
        return createErrorResponse(usersResult.message || '查询用户失败')
      }
      
      const users = usersResult.data || []
      if (users.length === 0) {
        return createErrorResponse('用户不存在', 1003)
      }
      
      const userId = users[0].id
      const updateData = {
        ...data,
        updated_at: new Date().toISOString()
      }
      
      if (updateData.settings) {
        updateData.settings = JSON.stringify(updateData.settings)
      }
      
      await database.update('users', updateData, 'id = ?', [userId])
      
      const userInfoResult = await this.getUserInfo()
      return userInfoResult
    } catch (error: any) {
      return createErrorResponse(error.message || '更新用户信息失败')
    }
  }
}

// 导出单例实例
export const userController = new UserController()